<template>
	<div>
		<ProTable
			ref="proTable"
			title="活动数据"
			:columns="columns"
			:request-api="getTableList"
			:dataCallback="dataCallback"
			:init-param="initParam"
			row-key="subscribeId"
		>
			<!-- 表格 功能 按钮 -->
			<template #otherButton>
				<el-button @click="onExport" v-auth="'activity:data:export:invoke'"> 导出 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" v-if="row.enableAudit && !row.isAudited" v-auth="'activity:data:audit:invoke'" link @click="onAudit(row)">
					审核
				</el-button>
			</template>
		</ProTable>
		<Audit :visible="auditVisible" :row="auditRow" @handleClose="closeAudit"></Audit>
	</div>
</template>

<script setup lang="tsx" name="activityData">
import { onMounted, ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchInviteDataList, fetchSettleInviteData, fetchExportInviteData } from '/@/api/activity';
import { useRouter, useRoute } from 'vue-router';
import { encryptPhoneNumber } from '/@/utils/commonFunction';
import { useDownload } from '/@/hooks/useDownload';
import Audit from './dialog/audit.vue';
import default_photo from '/@/assets/images/default_photo.jpg';

const router = useRouter();
const route = useRoute();

const auditVisible = ref(false);
const auditRow = ref();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'ID',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
		activityId: route.params.id,
	};
	return fetchInviteDataList(data);
};
const dataCallback = (res: any) => {
	res.records = res.records.map((item: any) => {
		const data = JSON.parse(item.customFormItems || '[]');
		Object.keys(data).map((v: any) => {
			item[v] = data[v];
		});
		return item;
	});

	if (res.total) {
		const customFormItems = JSON.parse(res.records[0].customFormItems || '[]');
		const neData = [
			{
				prop: 'keywords',
				label: '用户搜索',
				isShow: false,
				search: {
					span: 2,
					xs: 1,
					sm: 1,
					md: 2,
					lg: 1,
					xl: 1,
					render: (scope: any) => {
						const slot = {
							prepend: () => (
								<el-select
									v-model={scope.searchParam.searchType}
									placeholder="Select"
									style="width: 100px"
									onChange={(value) => {
										scope.searchParam.searchType = value;
									}}
								>
									{searchArr.map((item) => (
										<el-option key={item.value} label={item.label} value={item.value} />
									))}
								</el-select>
							),
						};
						return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={19}></el-input>;
					},
				},
			},
			{
				prop: 'userId',
				label: '用户ID',
			},
			{
				prop: 'userinfo',
				label: '用户信息',
				minWidth: 200,
				render: (scope) => {
					return (
						<div class="flex-center">
							<el-image src={scope.row.avatar || default_photo} style="width: 40px; height: 40px;flex-shrink:0" fit="cover"></el-image>
							<div style="text-align: left;" class="ml10">
								<el-link type="primary" underline={false} onClick={() => router.push(`/user/detail/${scope.row.userId}`)}>
									{scope.row.nickName}
								</el-link>
								<div>{encryptPhoneNumber(scope.row.phone) || '-'}</div>
							</div>
						</div>
					);
				},
			},
			{
				prop: 'userName',
				label: '姓名',
				minWidth: 100,
			},
			{
				prop: 'phone',
				label: '手机号',
				minWidth: 120,
				render: (scope: any) => {
					return encryptPhoneNumber(scope.row.phone) || '-';
				},
			},
			...customFormItems.map((item: any) => {
				return {
					prop: item.key,
					label: item.key,
					render: (scope: any) => {
						const customFormItems = JSON.parse(scope.row.customFormItems || '[]');
						const value = customFormItems.find((v: any) => v.key == scope.column.label)?.value;
						return value;
					},
				};
			}),
			{
				prop: 'enrollStatus',
				label: '报名状态',
				minWidth: 120,
				search: { el: 'select', props: { placeholder: '选择报名状态', clearable: true, filterable: true } },
				enum: [
					{
						label: '等待审核',
						value: 0,
					},
					{
						label: '报名成功',
						value: 1,
					},
					{
						label: '报名失败',
						value: 2,
					},
				],
				render: (scope: any) => {
					return scope.row.enrollStatus;
					return scope.row.enrollStatus == '报名失败' ? (
						<div>
							{scope.row.enrollStatus}
							<el-tooltip class="box-item" effect="light" content={scope.row.rejectReason} placement="top">
								<el-icon color="red" class="mt-3 ml5" style="vertical-align: middle;">
									<WarningFilled />
								</el-icon>
							</el-tooltip>
						</div>
					) : (
						scope.row.enrollStatus
					);
				},
			},
			{
				prop: 'signInStatus',
				label: '签到状态',
				minWidth: 120,
				search: { el: 'select', props: { placeholder: '选择签到状态', clearable: true, filterable: true } },
				enum: [
					{
						label: '未签到',
						value: false,
					},
					{
						label: '已签到',
						value: true,
					},
				],
			},
			{
				prop: 'giftStatus',
				label: '伴手礼状态',
				minWidth: 180,
				search: { el: 'select', props: { placeholder: '选择伴手礼状态', clearable: true, filterable: true } },
				enum: [
					{
						label: '待核销',
						value: false,
					},
					{
						label: '已核销',
						value: true,
					},
				],
				render: (scope: any) => {
					const { giftVerifyCode, giftStatus, signInStatus, enrollStatus, enableGift } = scope.row;
					return enableGift && signInStatus && enrollStatus == '报名成功' ? (
						<div>
							{giftVerifyCode}
							{giftStatus ? (
								<span class="ml5">已核销</span>
							) : (
								<el-button class="ml5" type="primary" v-auth={'activity:data:redeem:invoke'} link onClick={() => onWriteOff(scope.row)}>
									立即核销
								</el-button>
							)}
						</div>
					) : (
						''
					);
				},
			},
			{ prop: 'operation', label: '操作', fixed: 'right', width: 80, align: 'left' },
		];
		columns.value = neData;
	}
	return res;
};

const columns = ref<ColumnProps<any>[]>([
	{
		prop: 'keywords',
		label: '用户搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => {
								scope.searchParam.searchType = value;
							}}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={19}></el-input>;
			},
		},
	},
	{
		prop: 'userId',
		label: '用户ID',
	},
	{
		prop: 'userinfo',
		label: '用户信息',
		minWidth: 200,
		render: (scope) => {
			return (
				<div class="flex-center">
					<el-image src={scope.row.avatar || default_photo} style="width: 40px; height: 40px;flex-shrink:0" fit="cover"></el-image>
					<div style="text-align: left;" class="ml10">
						<el-link type="primary" underline={false} onClick={() => router.push(`/user/detail/${scope.row.userId}`)}>
							{scope.row.nickName}
						</el-link>
						<div>{encryptPhoneNumber(scope.row.phone) || '-'}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'userName',
		label: '姓名',
		minWidth: 100,
	},
	{
		prop: 'phone',
		label: '手机号',
		minWidth: 120,
		render: (scope: any) => {
			return encryptPhoneNumber(scope.row.phone) || '-';
		},
	},
	// {
	// 	prop: 'custom',
	// 	label: '自定义名称',
	// 	minWidth: 120,
	// },
	{
		prop: 'enrollStatus',
		label: '报名状态',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '选择报名状态', clearable: true, filterable: true } },
		enum: [
			{
				label: '等待审核',
				value: 0,
			},
			{
				label: '报名成功',
				value: 1,
			},
			{
				label: '报名失败',
				value: 2,
			},
		],
		render: (scope: any) => {
			return scope.row.enrollStatus;
			return scope.row.enrollStatus == '报名失败' ? (
				<div>
					{scope.row.enrollStatus}
					<el-tooltip class="box-item" effect="light" content={scope.row.rejectReason} placement="top">
						<el-icon color="red" class="mt-3 ml5" style="vertical-align: middle;">
							<WarningFilled />
						</el-icon>
					</el-tooltip>
				</div>
			) : (
				scope.row.enrollStatus
			);
		},
	},
	{
		prop: 'signInStatus',
		label: '签到状态',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '选择签到状态', clearable: true, filterable: true } },
		enum: [
			{
				label: '未签到',
				value: false,
			},
			{
				label: '已签到',
				value: true,
			},
		],
	},
	{
		prop: 'giftStatus',
		label: '伴手礼状态',
		minWidth: 180,
		search: { el: 'select', props: { placeholder: '选择伴手礼状态', clearable: true, filterable: true } },
		enum: [
			{
				label: '待核销',
				value: false,
			},
			{
				label: '已核销',
				value: true,
			},
		],
		render: (scope: any) => {
			const { giftVerifyCode, giftStatus, signInStatus, enrollStatus, enableGift } = scope.row;
			return enableGift && signInStatus && enrollStatus == '报名成功' ? (
				<div>
					{giftVerifyCode}
					{giftStatus ? (
						<span class="ml5">已核销</span>
					) : (
						<el-button class="ml5" type="primary" v-auth={'activity:data:redeem:invoke'} link onClick={() => onWriteOff(scope.row)}>
							立即核销
						</el-button>
					)}
				</div>
			) : (
				''
			);
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 80, align: 'left' },
]);

const searchArr = [
	{
		label: '用户ID',
		value: 'ID',
	},
	{
		label: '用户昵称',
		value: 'NAME',
	},
	{
		label: '手机号',
		value: 'PHONE',
	},
	{
		label: '核销码',
		value: 'CODE',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.searchType;
	});
	return target ? `输入${target?.label}搜索` : '';
});

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchExportInviteData, '活动数据', { ...proTable.value?.searchParam, activityId: route.params.id ? Number(route.params.id) : '' })
	);
};

const onAudit = (row: any) => {
	auditRow.value = row;
	auditVisible.value = true;
};

const closeAudit = (success: boolean) => {
	auditVisible.value = false;
	auditRow.value = null;
	if (success) {
		proTable.value?.getTableList();
	}
};

const onWriteOff = async (row: any) => {
	ElMessageBox.confirm('确认核销伴手礼?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchSettleInviteData({ id: row.subscribeId });
		if (res.code == 200) {
			ElMessage.success('核销成功');
			proTable.value?.getTableList();
		}
	});
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
